/**
 *  Copyright 2011 Miguel Ángel López Vicente 
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package cc.radio.app;

import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Clase encargada de obtener la información de cada
 * capítulo, como es es la imagen o la dirección 
 * del mp3
 */

public class Capitulo implements Serializable{

	private String urlmp3;
	private String titulo;
	private String urlimg;

	
	public Capitulo(Element html) {
		titulo = html.select(".contentheading").text();
		Elements mp3 = html.select(".phocadownloadfile32 a");
		
		if (mp3.size() > 0)
			urlmp3 = Radio.URL + mp3.get(0).attr("href");
		else
			urlmp3 = getUrlMp3(html.html());
		
		Elements img = html.select("img");
		if (img.size() > 0)
			urlimg = img.get(0).attr("src");
	}

	
	
	/**
	 * Devuelve la URL del MP3 del capítulo
	 * @return url mp3
	 */
	private String getUrlMp3(String s) {
		
		Matcher mp3 = Pattern.compile("images\\/stories\\/audio\\/([^&]+)").matcher(s);
		if (mp3.find())
			return Radio.URL+"/images/stories/audio/"+mp3.group(1).replace(" ", "%20");
		
		return null;
	}
	
	
	public String getUrlMp3() {
		return urlmp3;
	}
	
	/**
	 * Devuelve el bitmap de la foto del capítulo,
	 * si el capítulo no tiene imagen, devuelve null
	 * @return
	 */
	public Bitmap getBitmap() {
		if (urlimg == null)
			return null;

		try {
			
			URL url = new URL(Radio.URL + urlimg);
			URLConnection c = url.openConnection();
			InputStream in = c.getInputStream();
			
			//Debido a un problema al descodificador de JPG
			//hay que crear un array de bytes de la foto
			//en vez de usar directamente decodeStream
			
			int bytes = c.getContentLength();
			byte image[] = new byte[bytes];
			
			for (int i = 0; i < bytes; i++)
				image[i] = (byte) in.read();
			
			return BitmapFactory.decodeByteArray(image, 0, image.length);
		} catch (Exception e) {
			return null;
		}
	}
	
	
	public String getTitulo() {
		return titulo;
	}
	

	public boolean isValid(){
		return urlmp3 != null;
	}
	
	private static final long serialVersionUID = 5672679506898632889L;

}
